import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { WeatherData, HourlyForecast, DailyForecast, City } from '@/types/weather';

interface WeatherStore {
    currentWeather: WeatherData | null;
    hourlyForecast: HourlyForecast[];
    dailyForecast: DailyForecast[];
    selectedCity: City | null;
    savedCities: City[];
    isLoading: boolean;
    error: string | null;
    setCurrentWeather: (weather: WeatherData) => void;
    setForecasts: (hourly: HourlyForecast[], daily: DailyForecast[]) => void;
    setSelectedCity: (city: City) => void;
    addSavedCity: (city: City) => void;
    removeSavedCity: (cityId: string) => void;
    setLoading: (loading: boolean) => void;
    setError: (error: string | null) => void;
}

export const useWeatherStore = create<WeatherStore>()(
    persist(
        (set) => ({
            currentWeather: null,
            hourlyForecast: [],
            dailyForecast: [],
            selectedCity: null,
            savedCities: [],
            isLoading: false,
            error: null,
            setCurrentWeather: (weather) => set({ currentWeather: weather }),
            setForecasts: (hourly, daily) => set({
                hourlyForecast: hourly,
                dailyForecast: daily
            }),
            setSelectedCity: (city) => set({ selectedCity: city }),
            addSavedCity: (city) => set((state) => ({
                savedCities: [...state.savedCities, city]
            })),
            removeSavedCity: (cityId) => set((state) => ({
                savedCities: state.savedCities.filter(city => city.id !== cityId)
            })),
            setLoading: (loading) => set({ isLoading: loading }),
            setError: (error) => set({ error })
        }),
        {
            name: 'weather-store'
        }
    )
);